package com.stylefeng.guns.modular.analysis.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.json.GsonUtil;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.Dept;
import com.stylefeng.guns.common.persistence.model.Dict;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.common.persistence.model.QualityGradeRule;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.analysis.manager.AnalysisManager;
import com.stylefeng.guns.modular.analysis.manager.OptionManager;
import com.stylefeng.guns.modular.system.service.IDeptService;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * Created by jondai on 2018/1/21.
 */
@Controller
@RequestMapping("/analysis")
public class AnalysisController extends BaseController {

    private String PREFIX = "/analysis/";

    @Autowired
    private OptionManager optionManager;

    @Autowired
    private AnalysisManager analysisManager;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IDictService dictService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;


    @RequestMapping("/toTrainRatio")
    public String toFulltimeTrain(Model model){
        List<Dept> depts = deptService.getFirstLevelDept();
        List<Dict> laborTypes = dictService.getChildByCode(Const.LABOR_TYPE);
        List<Dict> posts = dictService.getByPName(Const.POST_TYPE);
        model.addAttribute("depts",depts);
        model.addAttribute("laborTypes",laborTypes);
        model.addAttribute("posts",posts);
        return PREFIX + "trainRatio.html";
    }

    @RequestMapping("/pointStartPage")
    public String pointStartPage(Model model){
        List<Dept> depts = deptService.getFirstLevelDept();
        List<Dict> posts = dictService.getByPName(Const.POST_TYPE);
        List<Dict> laborTypes = dictService.getChildByCode(Const.LABOR_TYPE);
        model.addAttribute("depts",depts);
        model.addAttribute("posts",posts);
        model.addAttribute("laborTypes",laborTypes);
        return PREFIX + "pointStart.html";
    }


    @RequestMapping("/pointRangePage")
    public String pointRangePage(Model model){
        return PREFIX + "pointRange.html";
    }

    /**
     * 培训的比重
     */
    @ResponseBody
    @RequestMapping("/trainRatioPip")
    public MvcResult trainRatioPip(String year, Employee employee){
        MvcResult mvcResult = new MvcResult();
        List<String> empCodes = new ArrayList<>();
        List<Employee> employees;

        employee.setDepartment("".equals(employee.getDepartment()) ? null : employee.getDepartment());
        employee.setTeam("".equals(employee.getTeam()) ? null : employee.getTeam());
        employee.setPlace("".equals(employee.getPlace()) ? null : employee.getPlace());
        employee.setPostType("".equals(employee.getPostType()) ? null : employee.getPostType());
        employee.setLaborType("".equals(employee.getLaborType()) ? null : employee.getLaborType());
        if(BeanUtils.checkFieldValueNull(employee)){
            employees = employeeService.selectList(null);
        }else{
            EntityWrapper<Employee> wrapper = new EntityWrapper<>();
            wrapper.setEntity(employee);
            employees = employeeService.selectList(wrapper);
        }

        employees.forEach(e -> empCodes.add(e.getEmpCode()));

//        Option test = optionManager.totalSubTrainPointPie(empCodes,year);
        List<Map<String, Object>> subTrainPip = optionManager.getSubTrainPip(empCodes, year);
        String format = GsonUtil.format(subTrainPip);
        List<String> tips = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : subTrainPip) {
            tips.add(stringObjectMap.get("name").toString());
        }
        Map<String,Object> result = new HashMap<>();
        result.put("series",format);
        result.put("total",employees.size());
        result.put("legend",GsonUtil.format(tips));
        mvcResult.setData(result);
        return mvcResult;
    }


    /**
     * 积分星级
     */
    @ResponseBody
    @RequestMapping("/pointStart")
    public MvcResult pointStart(String year, Employee employee){
        MvcResult mvcResult = new MvcResult();
        List<String> empCodes = new ArrayList<>();
        List<Employee> employees;

        employee.setDepartment("".equals(employee.getDepartment()) ? null : employee.getDepartment());
        employee.setTeam("".equals(employee.getTeam()) ? null : employee.getTeam());
        employee.setPlace("".equals(employee.getPlace()) ? null : employee.getPlace());
        employee.setPostType("".equals(employee.getPostType()) ? null : employee.getPostType());
        employee.setLaborType("".equals(employee.getLaborType()) ? null : employee.getLaborType());

        if(BeanUtils.checkFieldValueNull(employee)){
            employees = employeeService.selectList(null);
        }else{
            EntityWrapper<Employee> wrapper = new EntityWrapper<>();
            wrapper.setEntity(employee);
            employees = employeeService.selectList(wrapper);
        }

        employees.forEach(e -> empCodes.add(e.getEmpCode()));

//        Option poineStartOption = optionManager.pointStart(year,empCodes);
        String format = GsonUtil.format(optionManager.pointStart(year,empCodes));
        mvcResult.setData(format);
        return mvcResult;
    }

    /**
     * 积分范围
     */
    @ResponseBody
    @RequestMapping("/pointRange")
    public MvcResult pointRange(String year,  String empCodes){
        MvcResult mvcResult = new MvcResult();
        List<String> emplist = null;
        if(!StringUtils.isEmpty(empCodes)){
            String[] split = empCodes.split(",");
            emplist = Arrays.asList(split);
        }
        Map<String,Object> reslut=optionManager.pointRange(year,emplist);
        String format = GsonUtil.format(reslut);
        mvcResult.setData(format);
        return mvcResult;
    }


    /**
     * 导出培训档案
     * @param empCode
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/exportTrainFile")
    public void exportTrainFile(String empCode, String year, HttpServletResponse response){
        MvcResult mvcResult = new MvcResult();
        Map<String, Object> emp = getEmpMap(empCode);
        Map<String, Object> baseTrain = analysisManager.getBaseTrain(empCode,year);

        Map<String,Object> map = new HashMap<>();
        map.put("emp",emp);
        map.put("year",year);
        map.put("base",baseTrain);
        Double totalPoint = Double.valueOf(baseTrain.get("other_point").toString()) + Double.valueOf(baseTrain.get("base_point").toString());
        map.put("totalPoint",totalPoint);

        QualityGradeRule qualityGradeRule = new QualityGradeRule();
        qualityGradeRule.setGradeType(Const.TRAIN_START);
        EntityWrapper<QualityGradeRule> wrapper = new EntityWrapper<>();
        wrapper.setEntity(qualityGradeRule);
        wrapper.orderBy("integral");
        List<QualityGradeRule> qualityGradeRules = qualityGradeRuleService.selectList(wrapper);

        String star  = "一星";
        if(totalPoint < qualityGradeRules.get(0).getIntegral()){
            star  = "一星";
        }else if(totalPoint < qualityGradeRules.get(1).getIntegral()){
            star  = "二星";
        }else if(totalPoint < qualityGradeRules.get(2).getIntegral()){
            star  = "三星";
        }else if(totalPoint < qualityGradeRules.get(3).getIntegral()){
            star  = "四星";
        }else{
            star  = "五星";
        }
//        if(totalPoint >= 70 && ){
//            star  = "三星";
//        }
//        if(totalPoint >= 80 && totalPoint <90){
//            star  = "四星";
//        }
//        if(totalPoint >= 90){
//            star  = "五星";
//        }

        map.put("star",star);


//        String path=  AnalysisController.class.getClassLoader().getResource("").getPath();
//        String tempPath = path+"temp/";
//        String excelPath = path+"excel/";

        try {
            ApplicationHome home = new ApplicationHome(getClass());
            File jarFile = home.getSource();
            String tempPath = jarFile.getParent()+"/temp/";
            String excelPath = jarFile.getParent()+"/template/";
            System.out.println(excelPath);
            TemplateExportParams params = new TemplateExportParams(
                    excelPath+"员工培训档案模板.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params,map);

//            File savefile = new File(tempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
            String fileName = year+"-"+emp.get("empName")+"-员工培训档案.xlsx";
//            String filePathName  = tempPath + filename;

            OutputStream outputStream=response.getOutputStream();
//            String fileName="员工基本信息统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("download")
    public ResponseEntity<byte[]> download(String fileName) throws IOException {
        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        String tempPath = jarFile.getParent()+"/temp/";

        String path = tempPath + fileName;
        path = java.net.URLDecoder.decode(path,"utf-8");
        System.out.println(path);
        fileName = java.net.URLDecoder.decode(fileName,"gb2312");
        return super.renderFile(fileName,path);
    }


    public Map<String, Object> getEmpMap(String empCode) {
        Employee employee = employeeService.selectByCode(empCode);
        Map<String,Object> emp = new HashMap<>();
        emp.put("empName",employee.getEmpName());
        emp.put("empCode",employee.getEmpCode());
        Map<String, String> postTypeMap = dictService.getMapNumNameByPcode(Const.POST_TYPE_CODE);
        emp.put("postTye",postTypeMap.get(employee.getPostType()));
        emp.put("deptName",employee.getDeptName());
        emp.put("placeName",employee.getPlaceName());
        emp.put("post",employee.getPost());
        return emp;
    }
}
